﻿using System;
using System.Collections.Generic;
using System.Text;

namespace DotNetExtensions.Core.Helpers
{
    public class TypeInvoker
    {
        public string Module { get; set; }
        public string Clazz { get; set; }

        public TypeInvoker()
        {

        }
        public TypeInvoker(Type type)
        {
            var invoker = TypeHelper.TryParse(type);
            this.Clazz = invoker.Clazz;
            this.Module = invoker.Module;
        }

        public object Invoke(string method, bool ioc = false)
        {
            object invoker;
            if (ioc == false) invoker = TypeHelper.CreateInstance(Module, Clazz);
            else
            {
                Type type = TypeHelper.TryParse(Module, Clazz);
                invoker = IOC.RegistTypeResolver.Resolve(type);
            }
            if (invoker == null) throw new Exception($"`{Clazz}` not find at {Module}.");
            var methodInfo = invoker.GetType().GetMethod(method);
            if (methodInfo == null) throw new Exception($"Method `{method}` not find at `{Clazz}`");
            return methodInfo.Invoke(invoker, null);
        }
        public object Invoke(string method, bool ioc = false, params object[] parameters)
        {
            object invoker;
            if (ioc == false) invoker = TypeHelper.CreateInstance(Module, Clazz);
            else
            {
                Type type = TypeHelper.TryParse(Module, Clazz);
                invoker = IOC.RegistTypeResolver.Resolve(type);
            }
            if (invoker == null) throw new Exception($"`{Clazz}` not find at {Module}.");
            var methodInfo = invoker.GetType().GetMethod(method);
            if (methodInfo == null) throw new Exception($"Method `{method}` not find at `{Clazz}`");
            return methodInfo.Invoke(invoker, parameters);
        }
    }
}
